package com.ls.blog.service;

import com.alibaba.fastjson.JSON;
import com.ls.blog.entity.SysUser;
import com.ls.blog.exception.NofindUserException;
import com.ls.blog.api.LoginService;
import com.ls.blog.api.PassWordMatchService;
import com.ls.blog.api.SysUserService;
import com.ls.blog.utils.TokenUtils;
import com.ls.blog.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: myblog
 * @author: lishun
 * @create: 2021-07-08 07:44
 **/
@Service
@Slf4j
public class LoginServiceIml implements LoginService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PassWordMatchService passWordMatchService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public Map<String,Object> login(SysUser user) throws Exception {

        /**
         * 1、根据登录名来查找数据库,查找用户信息
         * 2、密码匹配
         * 3、生成token
         * 4、放入redis
         * 5、返回结果
         */
        if (user == null) {
            return null;
        }
        //用户名匹配
        SysUser baseUser = sysUserService.findByUsername(user.getUsername());
        if (baseUser == null) {
            throw new NofindUserException("用户不存在");
        }
        //密码校验
        if (!passWordMatchService.isMatch(user.getPassword(),baseUser.getPassword())){
            return null;
        }
        // 生成token
        String token = TokenUtils.createToken(baseUser);
        // 放入redis,分钟
        UserInfo userInfo = new UserInfo();
        userInfo.setId(baseUser.getId());
        userInfo.setAccount(baseUser.getAccount());
        userInfo.setAvatar(baseUser.getAvatar());
        userInfo.setNickname(baseUser.getNickname());
        redisTemplate.opsForValue().set("TOKEN_"+token,JSON.toJSONString(userInfo),1, TimeUnit.DAYS);
        // 返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("user",userInfo);
        return map;

    }


    /**
     * 用户退出
     * @param token
     */
    @Override
    public void logout( String token) {
        redisTemplate.delete("TOKEN_"+token);

    }
}
